package com.orangescape.yql.ws;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import java.util.logging.Logger;

@SuppressWarnings("serial")
public class YqlServlet extends HttpServlet
{
	private static final Logger log = Logger.getLogger(YqlServlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		log.info("Received GET request - "+req.getRequestURI());
		resp.setContentType("text/xml");
		if(req.getQueryString().equals("wsdl"))
		{
			BufferedReader reader = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("wsdl.xml")));
            String line;
            while ((line = reader.readLine()) != null) {
            	resp.getWriter().println(line);
            }
            reader.close();
		}
		else
		{
		}
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException 
	{
		log.info("Received POST request - "+req.getRequestURI());
		resp.setContentType("text/xml");
		try
		{
			SAXBuilder parser = new SAXBuilder();
			Document doc = parser.build(req.getInputStream());
			XMLOutputter out = new XMLOutputter();
			Namespace soapenv = 
			    Namespace.getNamespace("http://schemas.xmlsoap.org/soap/envelope/");
			Element body = doc.getRootElement().getChild("Body", soapenv);
			if(body == null)
				throw new Exception("Body tag not found in SOAP");
			Namespace urn = 
			    Namespace.getNamespace("urn:orangescape");
			Element yql = body.getChild("Yql", urn);
			if(yql == null)
				throw new Exception("Yql tag not found in SOAP");
			
			
			Element q = yql.getChild("q", urn);
			Element env = yql.getChild("env", urn);
			Element flatten = yql.getChild("flatten", urn);
			if(q == null)
				throw new IOException("Query 'q' not found");
			if(env == null)
				throw new IOException("Environment 'env' not found");
			
            String url = "http://query.yahooapis.com/v1/public/yql?q="
            		+URLEncoder.encode(q.getText(), "UTF-8")+"&env="+URLEncoder.encode(env.getText(), "UTF-8");
			Document resdoc = parser.build(new URL(url));
			Element results = resdoc.getRootElement().getChild("results");
			if(results == null)
				throw new Exception("results tag not found in yql response. inform me - mani.doraisamy@orangescape.com");
			yql.detach();
			List tobeAttached = results.getChildren();
			for(int i = 0; i < tobeAttached.size(); i++)
			{
				Object o = tobeAttached.get(i);
				if(o instanceof Element)
				{
					Element res = (Element)o;
					body.addContent(res.detach());
				}
			}
			log.info("Response for - "+req.getRequestURI()+"\n"+out.outputString(doc));
			resp.getWriter().println(out.outputString(doc));
		}
		catch(Exception e)
		{
			throw new IOException(e);
		}
		
	}
	
}
